package com.yanqu.road.server.manger.activity.zhenhuan;

import com.google.protobuf.ByteString;
import com.yanqu.road.dao.impl.activity.zhenhuan.GameZhenHuanFinishPartyDaoImpl;
import com.yanqu.road.dao.impl.activity.zhenhuan.GameZhenHuanPromotionDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.zhenhuan.GameZhenHuanPromotionData;
import com.yanqu.road.entity.activity.zhenhuan.ZhenHuanPromotionInfo;
import com.yanqu.road.entity.activity.zhenhuan.secondProcess.GameZhenHuanFinishPartyData;
import com.yanqu.road.entity.enums.activity.zhenhuan.eZhenHuanChildType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanFirstProcessConfig;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanPb;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanSecondProcessConfig;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanThirdProcessConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.pb.activity.ZhenHuanProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.game.service.GameService;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.zhenhuan.service.ZhenHuanPartyFinishSyncServiceCmd;
import com.yanqu.road.server.manger.activity.zhenhuan.service.ZhenHuanPromotionSyncServiceCmd;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public class ZhenHuanMgr extends TempMgr {
    private static Map<Integer, GameZhenHuanPromotionData> promotionDataMap = new ConcurrentHashMap<>();

    //key:partyId 结算时发到游戏服的茶话会
    private static Map<Long, GameZhenHuanFinishPartyData> partyInfoDataMap = new ConcurrentHashMap<>();
    private static List<GameZhenHuanFinishPartyData> needInsertPartyInfo = new ArrayList<>();
    private static AtomicBoolean isLoadPartyInfo = new AtomicBoolean(false);
    private static ThreadTaskManger threadTaskManger;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        if (null == threadTaskManger) {
            threadTaskManger = new ThreadTaskManger(1, "MusicRoomRankActivityMgr");
        }

        reloadPromotionData();
        reloadZhenHuanFinishPartyData();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        List<Integer> deleteList = new ArrayList<>();

        for (GameZhenHuanPromotionData promotionData : promotionDataMap.values()) {
            if (promotionData.isInsertOption()) {
                new GameZhenHuanPromotionDaoImpl().add(promotionData);
            } else if (promotionData.isUpdateOption()) {
                new GameZhenHuanPromotionDaoImpl().update(promotionData);
            }

            ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(promotionData.getActivityId());
            if (openActivityInfo == null) {//活动结束移出内存
                deleteList.add(promotionData.getActivityId());
            }
        }

        for (Integer activityId : deleteList) {
            promotionDataMap.remove(activityId);
        }

        List<GameZhenHuanFinishPartyData> saveList = new ArrayList<>();
        synchronized (needInsertPartyInfo) {
            saveList.addAll(needInsertPartyInfo);
            needInsertPartyInfo.clear();
        }
        if (!saveList.isEmpty()) {
            new GameZhenHuanFinishPartyDaoImpl().addBatch(saveList);
        }

        List<Long> removePartyList = new ArrayList<>();
        for (GameZhenHuanFinishPartyData finishPartyData : partyInfoDataMap.values()) {
            ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(finishPartyData.getActivityId());
            if (openActivityInfo == null) {//活动结束移出内存
                removePartyList.add(finishPartyData.getPartyId());
            }
        }

        for (Long partyId : removePartyList) {
            synchronized (partyInfoDataMap) {
                GameZhenHuanFinishPartyData finishPartyData = partyInfoDataMap.get(partyId);
                if (finishPartyData == null) {
                    continue;
                }
                ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(finishPartyData.getActivityId());
                if (openActivityInfo == null) {
                    partyInfoDataMap.remove(partyId);
                }
            }
        }

        return true;
    }

    public static void initService(GameService syncMessageService) {
        syncMessageService.addGameServiceCommand(GameProtocol.S_ZHENHUAN_PROMOTION_SYNC_CROSS_BACK, new ZhenHuanPromotionSyncServiceCmd());
        syncMessageService.addGameServiceCommand(GameProtocol.S_ZHENHUAN_SECOND_PROCESS_PARTY_FINISH_CROSS_BACK, new ZhenHuanPartyFinishSyncServiceCmd());
    }

    public static void reloadPromotionData() {
        getLogger().info("reloadPromotionData start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.ZhenHuan.getValue());
        if (openActivityInfoList.isEmpty()) {
            promotionDataMap = new ConcurrentHashMap<>();
        } else {
            Map<Integer, GameZhenHuanPromotionData> tempPromotionDataMap = new HashMap<>();
            for (ActivityInfo activityInfo : openActivityInfoList) {
                GameZhenHuanPromotionData promotionData = new GameZhenHuanPromotionDaoImpl().getGameZhenHuanPromotionData(activityInfo.getActivityId());
                if (promotionData != null) {
                    tempPromotionDataMap.put(promotionData.getActivityId(), promotionData);
                }
            }
            promotionDataMap = tempPromotionDataMap;
        }

        getLogger().info("reloadPromotionData end");
    }

    public static void reloadZhenHuanFinishPartyData() {
        getLogger().info("reloadZhenHuanFinishPartyData start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.ZhenHuan.getValue(), eZhenHuanChildType.Second.getValue());
        if (openActivityInfoList.isEmpty()) {
            partyInfoDataMap = new ConcurrentHashMap<>();
            isLoadPartyInfo.set(false);
        } else {
            ActivityInfo activityInfo = openActivityInfoList.get(0);
            Map<Long, GameZhenHuanFinishPartyData> tempMap = new GameZhenHuanFinishPartyDaoImpl().getGameZhenHuanFinishPartyDataMap(activityInfo.getActivityId());

            partyInfoDataMap = tempMap;
            isLoadPartyInfo.set(true);
        }

        getLogger().info("reloadZhenHuanFinishPartyData end");
    }

    public static GameZhenHuanPromotionData getPromotionData(int activityId) {
        ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (openActivityInfo == null) {
            return null;
        }
        GameZhenHuanPromotionData data = promotionDataMap.get(activityId);
        if (data == null) {
            synchronized (promotionDataMap) {
                data = promotionDataMap.get(activityId);
                if (data == null) {
                    data = new GameZhenHuanPromotionData(activityId, openActivityInfo.getChildType());
                    promotionDataMap.put(activityId, data);
                }
            }
        }
        return data;
    }

    public static void setPromotion(int activityId, List<ZhenHuanProto.ZhenHuanPromotionTemp> promotionTemps) {
        GameZhenHuanPromotionData promotionData = getPromotionData(activityId);
        if (promotionData == null) {
            return;
        }
        Map<Long, ZhenHuanPromotionInfo> promotionInfoMap = new HashMap<>();
        for (ZhenHuanProto.ZhenHuanPromotionTemp promotionTemp : promotionTemps) {
            ZhenHuanPromotionInfo promotionInfo = ZhenHuanPb.parsePromotionInfo(promotionTemp);
            promotionInfoMap.put(promotionInfo.getUserId(), promotionInfo);
        }
        promotionData.setPromotionInfoMap(promotionInfoMap);

        //如果是二阶段的晋升名单,同时三阶段有开活动,名单同步到三阶段所在的活动跨服,带上UserBaseInfo
        syncPromotionToCross(activityId);
    }

    public static void syncPromotionToCross(int activityId) {
        GameZhenHuanPromotionData promotionData = getPromotionData(activityId);
        if (promotionData == null) {
            return;
        }

        ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (openActivityInfo == null) {
            return;
        }
        if (openActivityInfo.getChildType() == eZhenHuanChildType.First.getValue()) {
            ZhenHuanSecondProcessConfig secondProcessConfig = ZhenHuanConfigMgr.getSecondProcessConfig();
            if (secondProcessConfig == null) {
                return;
            }

            ZhenHuanProto.CrossZhenHuanPromotionListSyncMsg.Builder syncMsg = ZhenHuanProto.CrossZhenHuanPromotionListSyncMsg.newBuilder();
            syncMsg.setActivityId(secondProcessConfig.getActivityId());

            for (ZhenHuanPromotionInfo promotionInfo : promotionData.getPromotionInfoMap().values()) {
                ZhenHuanProto.ZhenHuanPromotionTemp.Builder promotionTemp = ZhenHuanPb.parsePromotionTemp(promotionInfo);
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(promotionInfo.getUserId(), GameServer.getInstance().getServerId());
                if (userBaseInfo != null) {
                    promotionTemp.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }
                syncMsg.addPromotionList(promotionTemp);
            }

            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_ZHENHUAN_PROMOTION_LIST_SYNC, syncMsg));
        } else if (openActivityInfo.getChildType() == eZhenHuanChildType.Second.getValue()) {
            ZhenHuanThirdProcessConfig thirdProcessConfig = ZhenHuanConfigMgr.getThirdProcessConfig();
            if (thirdProcessConfig == null) {
                return;
            }

            ZhenHuanProto.CrossZhenHuanPromotionListSyncMsg.Builder syncMsg = ZhenHuanProto.CrossZhenHuanPromotionListSyncMsg.newBuilder();
            syncMsg.setActivityId(thirdProcessConfig.getActivityId());

            for (ZhenHuanPromotionInfo promotionInfo : promotionData.getPromotionInfoMap().values()) {
                ZhenHuanProto.ZhenHuanPromotionTemp.Builder promotionTemp = ZhenHuanPb.parsePromotionTemp(promotionInfo);
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(promotionInfo.getUserId(), GameServer.getInstance().getServerId());
                if (userBaseInfo != null) {
                    promotionTemp.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }
                syncMsg.addPromotionList(promotionTemp);
            }

            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_ZHENHUAN_PROMOTION_LIST_SYNC, syncMsg));
        }


    }

    /**
     * 三阶段开宴同步
     */
    public static void thirdProcessOpenBanquetNoticeSync(ZhenHuanProto.ZhenHuanThirdProcessOpenBanquetNoticeSyncMsg msg) {
        // 广播给在线玩家
        List<GamePlayer> userList = GamePlayerMgr.getAllOnlinePlayer();
        ZhenHuanProto.ZhenHuanThirdProcessOpenBanquetNoticeSyncMsg.Builder syncMsg = ZhenHuanProto.ZhenHuanThirdProcessOpenBanquetNoticeSyncMsg.newBuilder(msg);
        for (GamePlayer player : userList) {
            player.sendPacket(Protocol.U_ZHENHUAN_THIRD_PROCESS_OPEN_BANQUET_NOTICE_SYNC, syncMsg);
        }
    }

    /**
     * 是否有资格开启该阶段
     */
    public static boolean isActivityAble(long userId, int activityId) {
        ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (openActivityInfo == null) {
            return false;
        }

        if (openActivityInfo.getChildType() == eZhenHuanChildType.Second.getValue()) {
            //二阶段取一阶段晋升名单
            ZhenHuanFirstProcessConfig firstProcessConfig = ZhenHuanConfigMgr.getFirstProcessConfig();
            if (firstProcessConfig == null) {
                //一阶段没活动,默认有资格
                return true;
            }
            GameZhenHuanPromotionData gameZhenHuanPromotionData = promotionDataMap.get(firstProcessConfig.getActivityId());
            if (gameZhenHuanPromotionData == null) {
                return false;
            }
            return gameZhenHuanPromotionData.getPromotionInfoMap().containsKey(userId);
        }

        if (openActivityInfo.getChildType() == eZhenHuanChildType.Third.getValue()) {
            //三阶段取二阶段晋升名单,三阶段不能单独开,没二阶段活动默认没资格
            ZhenHuanSecondProcessConfig secondProcessConfig = ZhenHuanConfigMgr.getSecondProcessConfig();
            if (secondProcessConfig == null) {
                return false;
            }
            GameZhenHuanPromotionData gameZhenHuanPromotionData = promotionDataMap.get(secondProcessConfig.getActivityId());
            if (gameZhenHuanPromotionData == null) {
                return false;
            }
            return gameZhenHuanPromotionData.getPromotionInfoMap().containsKey(userId);
        }

        return false;
    }

    public static GameZhenHuanFinishPartyData getFinishPartyData(int activityId, long partyId) {
        ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (openActivityInfo == null) {
            return null;
        }
        if (openActivityInfo.getType() != eActivityType.ZhenHuan.getValue()) {
            return null;
        }
        if (openActivityInfo.getChildType() != eZhenHuanChildType.Second.getValue()) {
            return null;
        }

        if (isLoadPartyInfo.compareAndSet(false, true)) {
            reloadZhenHuanFinishPartyData();
        }

        GameZhenHuanFinishPartyData finishPartyData = partyInfoDataMap.get(partyId);
        if (finishPartyData != null && finishPartyData.getActivityId() == activityId) {
            return finishPartyData;
        }

        return null;
    }

    public static void addFinishPartyData(int activityId, GameZhenHuanFinishPartyData finishPartyData) {
        ActivityInfo openActivityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (openActivityInfo == null) {
            return;
        }
        if (openActivityInfo.getType() != eActivityType.ZhenHuan.getValue()) {
            return;
        }
        if (openActivityInfo.getChildType() != eZhenHuanChildType.Second.getValue()) {
            return;
        }

        synchronized (partyInfoDataMap) {
            partyInfoDataMap.put(finishPartyData.getPartyId(), finishPartyData);
        }

        synchronized (needInsertPartyInfo) {
            needInsertPartyInfo.add(finishPartyData);
        }
    }

    public static void addTask(int code, long userId, ByteString byteString) {
        addTask(code, userId, byteString.toByteArray());
    }

    public static void addTask(int code, long userId, byte[] bytes) {
        if (threadTaskManger != null) {
            threadTaskManger.addTask(0, new ZhenHuanTask(code, userId, bytes));
        }
    }
}
